package vip.zhenzicheng;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhenzicheng
 * @DESCRIPTION: 测试模拟
 * @DATE: 2022/04/24 5:19 PM
 */
@RestController
public class TestController {
  @Autowired
  CuratorFramework curatorFramework;
  @Autowired
  private OrderService orderService;
  @Value("${server.port}")
  private String port;

  @PostMapping("/stock/deduct")
  public Object reduceStock(Integer id) throws Exception {
    // 互斥锁
    InterProcessMutex interProcessMutex = new InterProcessMutex(curatorFramework, "/product_" + id);
    try {
      // ...一直等到加锁成功
      interProcessMutex.acquire();
      orderService.reduceStock(id);
    } catch (Exception e) {
      if (e instanceof RuntimeException) {
        throw e;
      }
    } finally {
      // 释放锁 放置死锁
      interProcessMutex.release();
    }
    return "ok:" + port;
  }
}
